<template>
	<u-popup :show="show" mode="bottom" :round="20" :closeOnClickOverlay="true" @open="onOpen" @close="onClose"
		closeable>
		<view class="confirm-popup">
			<!-- 头部标题 -->
			<view class="header">
				<text class="title">套餐兑换</text>
				<text class="subtitle">请核对收货地址和商品信息</text>
			</view>

			<!-- 地址卡片 -->
			<view class="card address-card" hover-class="pressed" @tap="handleAddressClick">
				<image class="addr-icon" src="@/static/images/icon-site.png" mode="widthFix" />
				<view class="addr-content">
					<template v-if="addressReady">
						<view class="addr-row">
							<text class="addr-name">{{ addressInfo.receiverName }}</text>
							<text class="addr-phone">{{ addressInfo.phone }}</text>
							<text v-if="addressInfo.isDefault" class="addr-tag">默认</text>
						</view>
						<text class="addr-detail">
							{{ addressInfo.province }}{{ addressInfo.city }}{{ addressInfo.district }}{{ addressInfo.detail }}
						</text>
					</template>
					<template v-else>
						<text class="addr-empty">去添加地址</text>
					</template>
				</view>
				<text class="addr-action">{{ addressReady ? '更换' : '新增' }}</text>
			</view>

			<!-- 商品卡片 -->
			<view class="card product-card">
				<image class="prod-img" v-if="detailInfo.imageUrl" :src="detailInfo.imageUrl" mode="aspectFill" />
				<view class="prod-info">
					<text class="prod-name u-line-2">{{ detailInfo.name || '商品名称' }}</text>
					<text class="prod-name u-line-2" style="color: gray;">{{ detailInfo.description || '商品描述' }}</text>
				</view>
			</view>

			<!-- 兑换信息 -->
			<view class="card redeem-card">
				<view class="redeem-title">兑换码信息</view>

				<!-- 卡号 -->
				<view class="field">
					<view class="field-label">卡号</view>
					<u--input v-model="redeem.cardNumber" placeholder="请输入卡号" clearable border="surround" type="text"
						:maxlength="32" />
				</view>

				<!-- 卡密 -->
				<view class="field">
					<view class="field-label">卡密</view>
					<u--input v-model="redeem.cardKey" placeholder="请输入卡密" clearable border="surround"
						:maxlength="64" />
				</view>

				<!-- 小提示 -->
				<view class="tips">
					• 粘贴时会自动去除空格<br />
					• 如多次失败，请检查大小写或与发卡方联系
				</view>
			</view>

			<!-- 底部操作栏 -->
			<view class="footer">
				<button class="buy-btn" :loading="submitting" @tap="handleBuy">
					{{ submitting ? '提交中...' : '立即兑换' }}
				</button>
			</view>
			<view class="safe-area" />
		</view>
	</u-popup>
</template>

<script>
	export default {
		name: 'ConfirmOrderPopup',
		props: {
			show: {
				type: Boolean,
				default: false
			},
			// 商品详情
			detailInfo: {
				type: Object,
				default: () => ({
					id: '',
					name: '',
					desc: '',
					price: 0,
					imageUrl: ''
				})
			},
			// 可选默认地址
			defaultAddress: {
				type: Object,
				default: () => null
			}
		},
		emits: ['update:show', 'toBuy', 'manageAddress'],
		data() {
			return {
				addressInfo: {},
				qty: 1,
				submitting: false,
				redeem: {
					comboId: "",
					userId: "",
					addressId: '',
					cardNumber: '',
					cardKey: ''
				}
			}
		},
		computed: {
			addressReady() {
				return this.addressInfo && this.addressInfo.id
			},
			priceNumber() {
				const p = Number(this.detailInfo.price || 0)
				return Number.isFinite(p) ? p : 0
			},
			priceText() {
				return '¥' + this.priceNumber.toFixed(2)
			},
			total() {
				return this.priceNumber * this.qty
			},
			totalText() {
				return '¥' + this.total.toFixed(2)
			}
		},
		watch: {
			show(val) {
				// 弹出时尝试读取地址（来源：props 或本地缓存）
				if (val) this.ensureAddress()
			},
			defaultAddress(val) {
				console.log(val, 'val--watch');
				this.addressInfo = val;

			}
		},
		methods: {
			onOpen() {
				this.$emit('update:show', true)
				this.ensureAddress()
			},
			onClose() {
				this.$emit('close', false)
			},
			ensureAddress() {
				// 优先用父级传入
				if (this.defaultAddress && this.defaultAddress.id) {
					this.addressInfo = this.defaultAddress
					return
				}
				// 其次尝试本地缓存（若你的项目有写入）
				try {
					const cached = uni.getStorageSync('defaultAddress')
					if (cached && cached.id) this.addressInfo = cached
				} catch (e) {
					// ignore
				}
			},
			handleAddressClick() {
				// 统一从这里跳转，父组件可监听去对应地址页
				this.$emit('manageAddress', this.addressReady ? 'choose' : 'add')
				const url = this.addressReady ?
					'/pages/mine/address/address?type=1' :
					'/pages/mine/address/addAddress'
				uni.navigateTo({
					url
				})
			},
			incQty() {
				this.qty += 1
			},
			decQty() {
				if (this.qty > 1) this.qty -= 1
			},
			async handleBuy() {
				if (!this.addressReady) {
					uni.showToast({
						title: '请先添加收货地址',
						icon: 'none'
					})
					return
				}
				if (!this.redeem.cardNumber) {
					uni.showToast({
						title: '请先输入卡号',
						icon: 'none'
					})
					return
				}
				if (!this.redeem.cardKey) {
					uni.showToast({
						title: '请先输入卡密',
						icon: 'none'
					})
					return
				}
				if (this.submitting) return
				this.submitting = true
				// 防抖 + 向父级传递订单信息
				this.redeem.comboId = this.detailInfo.id;
				this.redeem.addressId = this.addressInfo.id;
				this.redeem.userId = uni.getStorageSync('UserInfo').userId;
				try {
					this.$emit('handleBuy', this.redeem)
					// 成功后可关闭
					// this.$emit('update:show', false)
				} catch (e) {
					uni.showToast({
						title: '兑换失败，请重试',
						icon: 'none'
					})
				} finally {
					this.submitting = false
				}
			}
		},

	}
</script>

<style scoped lang="scss">
	.confirm-popup {
		padding: 24rpx 32rpx 0;
		background: #f7f8fa;
		border-radius: 20rpx;

		.header {
			margin-bottom: 20rpx;

			.title {
				font-size: 34rpx;
				font-weight: 600;
				color: #111;
			}

			.subtitle {
				margin-top: 6rpx;
				margin-left: 20rpx;
				font-size: 24rpx;
				color: #8c8c8c;
			}
		}

		.card {
			border-radius: 24rpx;
			background: #fff;
			padding: 24rpx;
			margin-bottom: 20rpx;
		}

		.field {
			display: flex;
			align-items: center;
			margin-top: 20rpx;
		}

		.field-label {
			margin-right: 20rpx;
		}

		.tips {
			margin-top: 20rpx;
			color: gray;
			font-size: 26rpx;
		}

		.address-card {
			display: flex;
			align-items: flex-start;
			position: relative;

			.addr-icon {
				width: 40rpx;
				margin-right: 16rpx;
			}

			.addr-content {
				flex: 1;
				min-height: 80rpx;

				.addr-row {
					display: flex;
					align-items: center;
					gap: 12rpx;
					margin-bottom: 8rpx;

					.addr-name {
						font-size: 28rpx;
						font-weight: 600;
						color: #111;
					}

					.addr-phone {
						font-size: 26rpx;
						color: #576b95;
					}

					.addr-tag {
						font-size: 20rpx;
						color: #fa5151;
						background: #ffecec;
						padding: 4rpx 10rpx;
						border-radius: 999rpx;
					}
				}

				.addr-detail {
					font-size: 24rpx;
					color: #666;
					line-height: 1.5;
				}

				.addr-empty {
					font-size: 26rpx;
					color: #576b95;
				}
			}

			.addr-action {
				position: absolute;
				right: 24rpx;
				top: 24rpx;
				font-size: 24rpx;
				color: #acacac;
			}
		}

		.product-card {
			display: flex;
			gap: 16rpx;

			.prod-img {
				width: 180rpx;
				height: 180rpx;
				border-radius: 16rpx;
				background: #f2f2f2;
				overflow: hidden;
			}

			.prod-info {
				flex: 1;
				display: flex;
				flex-direction: column;
				justify-content: space-between;

				.prod-name {
					font-size: 28rpx;
					color: #111;
					line-height: 1.4;
				}

				.prod-meta {
					display: flex;
					align-items: center;
					justify-content: space-between;

					.prod-price {
						font-size: 32rpx;
						color: #fa5151;
						font-weight: 700;
					}

					.qty {
						display: flex;
						align-items: center;
						gap: 10rpx;

						.qty-btn {
							width: 56rpx;
							height: 56rpx;
							line-height: 56rpx;
							text-align: center;
							border-radius: 12rpx;
							background: #f5f5f5;
							color: #333;
							border: 1rpx solid #eee;
						}

						.qty-btn:disabled {
							opacity: 0.5;
						}

						.qty-num {
							width: 60rpx;
							text-align: center;
							font-size: 28rpx;
							color: #111;
						}
					}
				}
			}
		}

		.summary {
			.summary-row {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 16rpx 4rpx;
				font-size: 26rpx;
				color: #333;

				&.total {
					border-top: 1rpx dashed #eee;
					margin-top: 8rpx;
					padding-top: 20rpx;

					.total-amt {
						font-size: 34rpx;
						color: #fa5151;
						font-weight: 700;
					}
				}
			}
		}

		.footer {
			position: sticky;
			bottom: 0;
			left: 0;
			right: 0;
			background: #fff;
			border-top-left-radius: 24rpx;
			border-top-right-radius: 24rpx;
			margin-top: 16rpx;
			padding: 20rpx 24rpx 24rpx;

			display: flex;
			align-items: center;
			justify-content: space-between;
			gap: 16rpx;

			.pay-amount {
				display: flex;
				align-items: baseline;

				.label {
					font-size: 24rpx;
					color: #666;
					margin-right: 8rpx;
				}

				.value {
					font-size: 36rpx;
					font-weight: 700;
					color: #fa5151;
				}
			}

			.buy-btn {
				min-width: 280rpx;
				height: 80rpx;
				line-height: 80rpx;
				border-radius: 999rpx;
				background: linear-gradient(90deg, #ff6b6b, #ff3d3d);
				color: #fff;
				font-size: 28rpx;
			}

			.buy-btn[disabled] {
				opacity: 0.6;
			}
		}

		.safe-area {
			height: env(safe-area-inset-bottom);
		}

		.pressed {
			opacity: 0.9;
		}
	}

	/* 文本两行省略（uView 里自带 u-line-2，如果没有可用以下写法）
.u-line-2 {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
*/
</style>